const axios = require('axios');
const { Ollama } = require('ollama');
const cheerio = require('cheerio');
const ollama = new Ollama({ host: 'http://192.168.0.9:11434' });

async function baiduSearch(keywords) {
  const searchUrl = 'https://s.taosha.club/search';
  try {
    // 生成完整请求 URL
    const params = new URLSearchParams({
      kw: keywords,
      page: 1
    });
    const fullUrl = `${searchUrl}?${params}`;
    console.log('[DEBUG] 实际请求URL:', fullUrl);

    const response = await axios.get(searchUrl, {
      params: { ...Object.fromEntries(params) }, // 透传参数
      headers: {
        'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-encoding': 'gzip, deflate, br, zstd',
        'accept-language': 'zh-CN,zh;q=0.9',
        'connection': 'keep-alive',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'cookie':' Hm_lvt_9702b2eceec92190b0d8a1c1b2c402b3=1746328410; Hm_lpvt_9702b2eceec92190b0d8a1c1b2c402b3=1746328410; HMACCOUNT=8E4B6E227F480D79; csrfToken=X-7m9cAadVWYAFW8ZoO9zoo_; Hm_lvt_e24fc6b4527a4f6477e6a2a4eec19ae9=1746328465; Hm_lpvt_e24fc6b4527a4f6477e6a2a4eec19ae9=1746328684',
        'host': 's.taosha.club',
        'origin': 'https://s.taosha.club',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
        'x-csrf-token': 'X-7m9cAadVWYAFW8ZoO9zoo_',
        'x-requested-with': 'XMLHttpRequest'
      },
      timeout: 5000
    });

    console.log('[DEBUG] 响应数据:', JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    console.error('[ERROR] 请求失败:', error.message);
    return { results: [] };
  }
}

function cleanBaiduUrl(originalUrl) {
  // 处理百度跳转链接（如：http://www.baidu.com/link?url=...）
  if (originalUrl.includes('baidu.com/link')) {
    const match = originalUrl.match(/url=([^&]+)/);
    return match ? decodeURIComponent(match[1]) : originalUrl;
  }
  return originalUrl;
}

// 在解析函数中调用
function parseResults(jsonData) {
  return jsonData.results
    .map(result => ({
      title: result.title,
      url: cleanBaiduUrl(result.url) // 清洗URL
    }))
    .filter(item => 
      !item.url.includes('baijiahao.baidu.com') && // 二次过滤
      !item.url.includes('zhidao.baidu.com')
    );
}

// 优化后的内容获取
async function fetchContent(url) {
  try {
    const headers = {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
      'Accept-Language': 'zh-CN,zh;q=0.9',
      'Accept-Encoding': 'gzip, deflate, br',
      'Connection': 'keep-alive',
      'Sec-Fetch-Dest': 'document',
      'Sec-Fetch-Mode': 'navigate',
      'Sec-Fetch-Site': 'same-origin',
      'Sec-Fetch-User': '?1',
      'Upgrade-Insecure-Requests': '1'
    };
    const { data } = await axios.get(url, { 
      timeout: 5000,
      headers: headers// 绕过反爬
    });
    const $ = cheerio.load(data);
    return $('body').text()
      .replace(/\s+/g, ' ')
      .substring(0, 2000)
      .trim();
  } catch (error) {
    console.error(`内容获取失败 [${url}]: ${error.message}`);
    return '';
  }
}

// 主流程优化
async function main(question) {
  try {
    const searchData = await baiduSearch(question);
    const links = parseResults(searchData);
    
    // URL清洗和过滤
    // const validLinks = links
    //   .map(link => ({ ...link, url: cleanUrl(link.url) }))
    //   .filter(link => link.url);

    // if (validLinks.length === 0) {
    //   throw new Error('没有找到有效搜索结果');
    // }

    // 并行获取内容并过滤空结果
   // 修复点：分离 await 和 filter
   const rawContents = await Promise.all(
    links.map(link => fetchContent(link.url))
  );
  
  // 过滤无效内容（空字符串或 null）
  const contents = rawContents.filter(content => content && content.trim().length > 0);

    // 构建提示词
    const context = contents.join('\n\n--- 内容分割 ---\n\n');
    const { message } = await ollama.chat({
      model: 'qwq', // 使用实际安装的模型
      messages: [{
        role: 'user',
        content: `请基于以下搜索内容，用中文简明地回答这个问题：${question}\n\n搜索内容：\n${context}`
      }]
    });

    return {
      answer: message.content,
      references: validLinks.map(link => link.url)
    };
  } catch (error) {
    console.error(`处理失败: ${error.message}`);
    return { error: '无法生成答案，请稍后重试' };
  }
}

// 执行示例
main('2025年人工智能最新发展趋势')
  .then(result => {
    if (result.answer) {
      console.log('答案：\n', result.answer);
      console.log('\n参考链接：\n', result.references.join('\n'));
    } else {
      console.error(result.error);
    }
  })
  .catch(console.error);